from google.appengine.ext import db

from django.contrib.auth.models import get_hexdigest, check_password

import logging

class User(db.Model):
    """A User document that aims to mirror most of the API specified by Django
    at http://docs.djangoproject.com/en/dev/topics/auth/#users
    """
    email = db.StringProperty(required=True)
    password = db.StringProperty()
    name = db.StringProperty()
    shared_account_ids = db.ListProperty(long)
    is_active = db.BooleanProperty(default=True)
    last_login = db.DateTimeProperty(auto_now=True)
    date_joined = db.DateTimeProperty(auto_now_add=True)

    @property
    def id(self):
        return self.key().id()

    def __unicode__(self):
        return self.name

    def __str__(self):
        return unicode(self).encode('utf-8')

    def __repr__(self):
        return '<User: %s>' % str(self)

    def get_full_name(self):
        """Returns the users first and last names, separated by a space.
        """
        #full_name = u'%s %s' % (self.first_name or '', self.last_name or '')
        #return full_name.strip()
        return name

    def is_anonymous(self):
        return False

    def is_authenticated(self):
        return True

    def set_password(self, raw_password):
        """Sets the user's password - always use this rather than directly
        assigning to :attr:`~mongoengine.django.auth.User.password` as the
        password is hashed before storage.
        """
        import random
        algo = 'sha1'
        salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5]
        hsh = get_hexdigest(algo, salt, raw_password)
        self.password = '%s$%s$%s' % (algo, salt, hsh)

    def check_password(self, raw_password):
        """Checks the user's password against a provided password - always use
        this rather than directly comparing to
        :attr:`~mongoengine.django.auth.User.password` as the password is
        hashed before storage.
        """
        return check_password(raw_password, self.password)

    @classmethod
    def create_user(cls, email, password, name=None):
        """Create (and save) a new user with the given username, password and
        email address.
        """
        logging.info("email: %s, password: %s, name: %s" % (email, password, name))
        # Normalize the address by lowercasing the domain part of the email
        # address.
        if name is None:
            name, _ = email.strip().split('@', 1)

        user = User(email=email, name=name)
        user.set_password(password)
        user.put()
        return user

    def get_and_delete_messages(self):
        return []

